package com.dyava.commons.file;

import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;

import java.io.*;


public class FileStoreLocal implements FileStore {

	private String basePath="";
	
	public String getBasePath() {
		return basePath;
	}

	public void setBasePath(String basePath) {
		if(basePath==null){
			throw new RuntimeException("basePath 不能为空");
		}
		basePath = FilenameUtils.separatorsToUnix(basePath);
 		this.basePath = FilenameUtils.normalizeNoEndSeparator(basePath);
	}

	@Override
	public String save(String dir,String fileName, InputStream ism) throws IOException {
		if(StringUtils.isBlank(fileName)){
			fileName="dat";
		}
		if(StringUtils.isBlank(dir)){
			throw new IOException("dir 不能为空");
		}
		dir = FilenameUtils.separatorsToUnix(dir);
		String fulldir = FilenameUtils.concat(basePath, dir);
		File fdir = new File(fulldir);
		fdir.mkdirs();
		String fullfile = FilenameUtils.concat(fulldir, fileName);
		FileOutputStream osm = new FileOutputStream(fullfile);
		IOUtils.copy(ism, osm);
		IOUtils.closeQuietly(osm);
		return FilenameUtils.separatorsToUnix(fullfile);
	}

	@Override
	public String saveData(String dir,String fileName, byte[] data) throws IOException {
		if(StringUtils.isBlank(fileName)){
			fileName="dat";
		}
		if(StringUtils.isBlank(dir)){
			throw new IOException("dir 不能为空");
		}
		dir = FilenameUtils.separatorsToUnix(dir);
		String fulldir = FilenameUtils.concat(basePath, dir);
		File fdir = new File(fulldir);
		fdir.mkdirs();
        String fullfile = FilenameUtils.concat(fulldir, fileName);
		FileUtils.writeByteArrayToFile(new File(fullfile), data);
        return FilenameUtils.separatorsToUnix(fullfile);
	}

	@Override
	public InputStream load(String mark) throws IOException {
		if(StringUtils.isBlank(mark)){
			throw new IOException("mark 不能为空");
		}
		String fullfile = FilenameUtils.concat(basePath, mark);
		InputStream ism = new FileInputStream(fullfile);
		return ism;
	}

	@Override
	public byte[] loadData(String mark) throws IOException {
		if(StringUtils.isBlank(mark)){
			throw new IOException("mark 不能为空");
		}
		String fullfile = FilenameUtils.concat(basePath, mark);
		byte[] data = FileUtils.readFileToByteArray(new File(fullfile));
		return data;
	}

}
